/* 2019/6/27 0:48. by soft */

// 进度条工具
function Progress(selector, color) {
  this.dom = dom(selector);
  this.color = color || '#1ec5cf';
  this.width = 300;
  this.height = 80;
  this.canvas = null;
  this.init()
}
Progress.prototype = {
  init: function () {
    this.canvas = document.createElement('canvas');
    this.canvas.height = this.dom.clientHeight;
    this.canvas.width = this.dom.clientWidth;
    this.width = this.canvas.width;
    this.height = this.canvas.height;
    this.dom.appendChild(this.canvas);
    this.update(0)
  },
  update: function (rate) {
    if (rate > 1) rate = 1;
    var r = parseFloat(rate);
    var w = (r * this.width).toFixed(0);
    var ctx = this.canvas.getContext('2d');
    ctx.clearRect(0, 0, this.width, this.height);
    ctx.fillStyle = this.color;
    ctx.beginPath();
    ctx.fillRect(0, 0, w, this.height);
    var txt = (r * 100).toFixed(1) + "%";
    var tw = ctx.measureText(txt).width;
    ctx.font = '15px 黑体';
    ctx.fillStyle = '#ffffff';
    ctx.fillText(txt, ((this.width - tw) / 2), this.height - 5)
  }
};

function dom(selector, multi) {
  if (multi) {
    return document.querySelectorAll(selector)
  }
  return document.querySelector(selector)
}